package pers.chao.tool.encrypt;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.chao.tool.infrastructure.BytesUtil;

import java.io.File;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Description: md5、sha
 *
 * @author W.Chao
 * @date 2020/11/8 20:06
 **/
public final class EasyEncrypt {
	private static final Logger logger = LoggerFactory.getLogger(EasyEncrypt.class);

	private EasyEncrypt() {
	}

	private final static String MD5 = "MD5"; // md5容易碰撞，安全性不如其他两种高

	private final static String SHA1 = "SHA-1"; // 安全性和加密耗时适中，2017出现碰撞

	private final static String SHA256 = "SHA-256"; // 安全性高，加密耗时高

	private final static String SHA512 = "SHA-512";

	public static String md5(String text) {
		return combination(text.getBytes(), MD5);
	}

	public static String md5(byte[] bytes) {
		return combination(bytes, MD5);
	}

	public static String md5(File file) {
		return combination(BytesUtil.file2ByteArray(file), MD5);
	}

	public static String md5(InputStream stream) {
		return combination(BytesUtil.stream2ByteArray(stream), MD5);
	}

	public static String sha1(String text) {
		return combination(text.getBytes(), SHA1);
	}

	public static String sha1(byte[] bytes) {
		return combination(bytes, SHA1);
	}

	public static String sha1(File file) {
		return combination(BytesUtil.file2ByteArray(file), SHA1);
	}

	public static String sha1(InputStream stream) {
		return combination(BytesUtil.stream2ByteArray(stream), SHA1);
	}

	public static String sha256(String text) {
		return combination(text.getBytes(), SHA256);
	}

	public static String sha256(byte[] bytes) {
		return combination(bytes, SHA256);
	}

	public static String sha256(File file) {
		return combination(BytesUtil.file2ByteArray(file), SHA256);
	}

	public static String sha256(InputStream stream) {
		return combination(BytesUtil.stream2ByteArray(stream), SHA256);
	}

	public static String sha512(String text) {
		return combination(text.getBytes(), SHA512);
	}

	public static String sha512(byte[] bytes) {
		return combination(bytes, SHA512);
	}

	public static String sha512(File file) {
		return combination(BytesUtil.file2ByteArray(file), SHA512);
	}

	public static String sha512(InputStream stream) {
		return combination(BytesUtil.stream2ByteArray(stream), SHA512);
	}

	public static String encrypt(String value, String algorithm) {
		try {
			// 拿到转换器
			MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
			// 输入的字符串转换成字节数组
			byte[] inputByteArray = value.getBytes();
			return encryptCalculate(inputByteArray, messageDigest);
		} catch (NoSuchAlgorithmException e) {
			logger.warn("MessageDigest con not get this algorithm MessageDigest, input algorithm is {}", algorithm);
			return null;
		}
	}

	private static String combination(byte[] inputByteArray, String algorithm) {
		MessageDigest messageDigest = getMessageDigest(algorithm);
		return messageDigest != null ? encryptCalculate(inputByteArray, messageDigest) : null;
	}

	private static MessageDigest getMessageDigest(String algorithm) {
		try {
			return MessageDigest.getInstance(algorithm);
		} catch (NoSuchAlgorithmException e) {
			logger.warn("MessageDigest con not get this algorithm MessageDigest, input algorithm is {}", algorithm);
			return null;
		}
	}

	private static String encryptCalculate(byte[] inputByteArray, MessageDigest messageDigest) {
		// inputByteArray是输入字符串转换得到的字节数组
		messageDigest.update(inputByteArray);
		// 转换并返回结果，也是字节数组，包含16个元素
		byte[] resultByteArray = messageDigest.digest();
		// 字符数组转换成字符串返回
		return byteArrayToHex(resultByteArray);
	}

	private static String byteArrayToHex(byte[] byteArray) {

		// 首先初始化一个字符数组，用来存放每个16进制字符
		char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F'};
		// new一个字符数组，这个就是用来组成结果字符串的（解释一下：一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方））
		char[] resultCharArray = new char[byteArray.length * 2];
		// 遍历字节数组，通过位运算（位运算效率高），转换成字符放到字符数组中去
		int index = 0;
		for (byte b : byteArray) {
			resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
			resultCharArray[index++] = hexDigits[b & 0xf];
		}
		// 字符数组组合成字符串返回
		return new String(resultCharArray);
	}

}
